/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.gov.ana.facade;

import br.gov.ana.entities.Rio;
import br.gov.ana.entities.Subbacia;
import br.gov.ana.entities.SubbaciaRio;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

/**
 *
 * @author lucas.nunes
 */
@Stateless
public class SubbaciaRioFacade extends AbstractFacade<SubbaciaRio> {

    @PersistenceContext(unitName = "ResolucaoConjunta032010PU")
    private EntityManager em;

    @Override
    protected EntityManager getEntityManager() {
        return em;
    }

    public SubbaciaRioFacade() {
        super(SubbaciaRio.class);
    }

    public List<Rio> findRioBySubbacia(Subbacia subbacia) {
        try {
            // Retorna todos os rios vinculados a subbacia informada. (Ordena pela nome do Rio)            
            Query q = em.createQuery("SELECT s.sbrRioCd FROM SubbaciaRio s WHERE s.sbrDnsCd = :sbrDnsCd ORDER BY s.sbrRioCd.rioNm");
            q.setParameter("sbrDnsCd", subbacia);

            return q.getResultList();
        } catch (Exception e) {
            return null;
        }
    }

    public Subbacia findSubbaciaByRio(Rio rio) {
        try {

            Query q = em.createQuery("SELECT s.sbrDnsCd FROM SubbaciaRio s WHERE s.sbrRioCd = :sbrRioCd");
            q.setParameter("sbrRioCd", rio);

            q.setFirstResult(0);
            return (Subbacia) q.getSingleResult();
        } catch (Exception e) {
            return null;
        }
    }
}
